/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package elaborate.vwbe.impl;

import elaborate.vwbe.scripting.ScriptEngineContext;
import elaborate.vwbe.scripting.ScriptEventListener;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author lendle
 */
public class DefaultScriptEngineContext implements ScriptEngineContext{
    private List<ScriptEventListener> scriptEventListeners=new ArrayList<ScriptEventListener>();
    public void fireEvent(String eventName, Object... args) {
        for(ScriptEventListener l : this.scriptEventListeners){
            l.onEvent(eventName, args);
        }
    }
    /**
     * used for JavaScript array
     * @param eventName
     * @param o should actually a NativeArray instance
     */
    public void fireEvent(String eventName, Object o) {
        if(o.getClass().getName().equals("sun.org.mozilla.javascript.internal.NativeArray")){
            try{
                Method getLengthMethod=o.getClass().getMethod("getLength", new Class[0]);
                Method getIdsMethod=o.getClass().getMethod("getIds", new Class[0]);
                Method getMethod=o.getClass().getMethod("get", new Class[]{int.class, Object.class});
                Object[] array = new Object[(Integer) getLengthMethod.invoke(o, new Object[0])];
                for (Object _o : (Object [])getIdsMethod.invoke(o, new Object[0])) {
                    int index = (Integer) _o;
                    array[index] = getMethod.invoke(o, new Object[]{index, null});
                }
                this.fireEvent(eventName, array);
            }catch(Exception e){}
        }
    }
    
    public void addScriptEventListener(ScriptEventListener l) {
        this.scriptEventListeners.add(l);
    }

    public void removeScriptEventListener(ScriptEventListener l) {
        this.scriptEventListeners.remove(l);
    }
    
    /*public void test(Object o){
        System.out.println("test: "+o);
    }*/
    
}
